// @login 和 register
const express = require("express");
const router = express.Router();
const bcrypt = require("bcrypt");
const gravatar = require('gravatar');
const jwt = require('jsonwebtoken');
const keys = require("../config/keys");
const passport = require("passport");
const User = require("../models/user");

// $route get 请求 api/users/test
// @desc 返回请求的json数据
// @access public 
router.get("/test", (req, res) => {
    res.json({ msg: "test success!!!" })
})

// $route get 请求 api/users/register
// @desc 返回请求的json数据
// @access public 
router.post("/register", (req, res) => {
    //查询数据库是否有数据
    User.findOne({ email: req.body.email }).then((user) => {
        if (user) {
            return res.status(400).json("邮箱被注册")
        } else {
            const avatar = gravatar.url(req.body.email, { s: '200', r: 'pg', d: 'mm' });
            const newUser = new User({
                username: req.body.username,
                email: req.body.email,
                avatar,
                password: req.body.password,
                identity: req.body.identity
            });
            bcrypt.genSalt(10, function (err, salt) {
                bcrypt.hash(newUser.password, salt, (err, hash) => {
                    // Store hash in your password DB.
                    if (err) throw err;
                    newUser.password = hash;
                    newUser.save().then(user => res.json(user)).catch(err => console.log(err))
                });
            });
        }
    })
})

// $route post 请求 api/users/login
// @desc 返回token jwt passport
// @access public 
router.post("/login", (req, res) => {
    const email = req.body.email;
    const password = req.body.password;
    User.findOne({ email }).then(user => {
        if (!user) {
            return res.status(404).json("用户不存在");
        } else {
            // 密码匹配
            bcrypt.compare(password, user.password).then(isMatch => {
                if (isMatch) {
                    // 创建token规则
                    const rule = {
                        id: user.id,
                        username: user.username,
                        avatar: user.avatar,
                        identity: user.identity
                    };
                    jwt.sign(rule, keys.secretOrkey, { expiresIn: 3600 }, (err, token) => {
                        if (err) throw err;
                        res.json({
                            success: true,
                            token: "Bearer " + token
                        });
                    })
                } else {
                    return res.status(400).json("密码错误！");
                }
            })
        }
    })
})

// $route get 请求 api/users/current 用户信息
// @desc 返回 current user
// @access private
router.get("/current", passport.authenticate("jwt", { session: false }), (req, res) => {
    res.json({
        id: req.user.id,
        username: req.user.username,
        email: req.user.email,
        identity: req.user.identity
    });
})

// $route post 请求 api/users/updataPassword 更改密码
// @desc 返回 新密码
// @access private
router.post("/updataPassword", (req, res) => {
    let newPassword = req.body.password;
    bcrypt.genSalt(10, function (err, salt) {
        bcrypt.hash(newPassword, salt, (err, hash) => {
            if (err) throw err;
            newPassword = hash;
            User.update({ _id: req.body.id }, { $set: { password: newPassword } }, (error) => {
                if (error) {
                    res.json({ message: '密码修改失败' })
                }
                else {
                    res.json({ message: '密码修改成功' })
                }
            })
        });
    });

})

module.exports = router;